package com.sunchangming.stmdb.recman;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import junit.framework.Assert;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import com.google.protobuf.CodedInputStream;
import com.google.protobuf.CodedOutputStream;
import com.sunchangming.stmdb.TestUtil;

public class TestBlockIo {
	private static java.util.Random rand = new java.util.Random();
	private static java.nio.file.Path dir;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		dir = Paths.get("TestBlockIo");
		TestUtil.deleteDir(dir);
		Files.createDirectory(dir);
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
		TestUtil.deleteDir(dir);
	}

	@Before
	public void setUp() throws Exception {

	}

	@After
	public void tearDown() throws Exception {
	}

	private static BlockIo createBlockIo() {
		final long blockId = rand.nextLong();
		final byte[] data = new byte[8192];
		rand.nextBytes(data);
		final BlockIo b = new BlockIo(blockId, data);
		return b;
	}

	@Test
	public void testReadWrite() throws IOException, RuntimeException, FileNotFoundException {
		final BlockIo b = createBlockIo();

		{
			final FileOutputStream fs = new FileOutputStream(dir.resolve("test.bin").toFile());
			final CodedOutputStream cos = CodedOutputStream.newInstance(fs);
			b.write(cos);
			cos.flush();
			fs.close();
		}
		{
			final FileInputStream fs = new FileInputStream(dir.resolve("test.bin").toFile());
			final CodedInputStream cis = CodedInputStream.newInstance(fs);
			final BlockIo b2 = BlockIo.read(cis);
			fs.close();
			Assert.assertTrue(b.isSameData(b2));
		}
	}

	@Test
	public void testSetBlockId() {
		final BlockIo b = createBlockIo();
		final long blockid = rand.nextLong();
		b.setBlockId(blockid);
		Assert.assertEquals(blockid, b.getBlockId());
	}

}
